package com.leyou.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private FastFileStorageClient storageClient;//fastDFS访问的客户端对象

    @Override
    public String upload(MultipartFile file) {
        try {
            Set<String> ext = new HashSet<>();
            ext.add("image/jpeg");
            ext.add("image/jpg");
            ext.add("image/png");

            //校验文件类型
            String contentType = file.getContentType();//获取内容类型
            if (!ext.contains(contentType)) {
                System.out.println("文件类型不匹配,请校验" + contentType);
            }
            //校验文件内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                System.out.println("文件内容不匹配,请校验" + contentType);
            }
            //实现文件上传逻辑
            //保存到本地
//            file.transferTo(new File("F:/aaaaatest/" + System.currentTimeMillis() + file.getOriginalFilename()));
            //先获取文件名
            String originalFilename = file.getOriginalFilename();
            //这个方法就是截取最后一个.点后面的内容
            String ext1 = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext1, null);
            return "http://image.leyou.com/" + storePath.getFullPath();//得到完整路径并返回
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
